const connectiondb = require('../sql/mysql')

/* 
TODO 获取读者信息
*/
async function queryAll(req, res) {
    const result = await connectiondb('select * from reader_info', [])
    res.send({ code: 200, msg: '获取读者信息成功', data: result })
}

/* 
TODO 增添读者信息
*/
async function add(req, res) {
    const { reader_name, sex, telephone, card } = req.body;
    const sql = 'insert into reader_info value(null,?,?,?,?)';
    await connectiondb(sql, [reader_name, sex, telephone, card])
    res.send({ code: 200, msg: '添加读者信息成功' })
}
/* 
TODO 删除读者信息
*/
async function del(req, res) {
    const {idd} = req.body;
    // const reader_id1=reader_id.idd
    const sql = 'delete from reader_info where reader_id=?'
    await connectiondb(sql,[idd])
    res.send({code:200,msg:'删除成功'})
}
/* 
TODO 根据读者ID查询读者信息
*/
async function queryOne(req,res){
    const {reader_id}=req.body;
    const sql='select * from reader_info where reader_id=?'
    const result= await connectiondb(sql,[reader_id])
    res.send({code:200,msg:'根据ID获取读者信息成功',data:result[0]})
}
/* 
TODO 修改读者信息
*/
async function update(req,res){
    const{did,nameid,sexid,phoneid,cardid}=req.body;
    const sql='update reader_info set reader_name=?,sex=?,telephone=?,card=? where reader_id=?'
    await connectiondb(sql,[nameid,sexid,phoneid,cardid,did])
    res.send({code:200,msg:'修改读者信息成功'})
}

/* 
TODO 根据读者性别查询读者信息
*/
async function queryByGender(req,res){
    const {sex}=req.body;
    const sql='select * from reader_info where sex=?'
    const result=await connectiondb(sql,[sex])
    res.send({code:200,msg:'获取读者信息成功',data:result})
}
/* 
TODO 根据读者姓名进行模糊查询
*/
async function likename(req,res){
   const {reader_name}=req.body;
   const sql=`select * from reader_info where reader_name like '%${reader_name}%'`;
   const result=await connectiondb(sql,[])
   res.send({code:200,msg:'模糊查询成功',data:result})
}

module.exports = {
    queryAll,
    add,
    del,
    update,
    queryOne,
    queryByGender,
    likename
}